package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.ReportMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class reportServiceImpl implements ReportService {
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkSpaceService workSpaceService;

    @Override
    public TurnoverReportVO getTurenover(LocalDate begin, LocalDate end) {
        List<LocalDate> datelist =new ArrayList();
        datelist.add(begin);
        do {
            //日期计算，获得指定日期后1天的日期
            begin = begin.plusDays(1);
            datelist.add(begin);
        } while (!begin.equals(end));
        List<Double> doubles = new ArrayList<>();
        for (LocalDate date : datelist) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询营业额
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begin",beginTime);
            map.put("end",endTime);
          Double turnover =  reportMapper.sumBymap(map);
          turnover = turnover == null ? 0.0 : turnover;
            doubles.add(turnover);
        }


        return   //封装数据
                TurnoverReportVO.builder()
                        .dateList(StringUtils.join(datelist,","))
                        .turnoverList(StringUtils.join(doubles,","))
                        .build();
    }
    /*
     * 统计用户数据
     * */
    @Override
    public UserReportVO getUserstatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> datalist =new ArrayList();
        datalist.add(begin);
        do {
            //日期计算，获得指定日期后1天的日期
            begin = begin.plusDays(1);
            datalist.add(begin);
        } while (!begin.equals(end));
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUSerlist = new ArrayList<>();
        for (LocalDate date : datalist) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            //查询总用户量
            map.put("end",endTime);
            Integer countlist= userMapper.userBymap(map);
            //查询新用户
            map.put("beng",beginTime);
            Integer newuser = userMapper.userBymap(map);
            totalUserList.add(countlist);
            newUSerlist.add(newuser);
        }

        return UserReportVO.builder()
                .newUserList(StringUtils.join(newUSerlist,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .dateList(StringUtils.join(datalist,","))
                .build();
    }
    /*
     * 统计订单数据
     * */
    @Override
    public OrderReportVO getordersstatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> datalist =new ArrayList();
        datalist.add(begin);
        do {
            //日期计算，获得指定日期后1天的日期
            begin = begin.plusDays(1);
            datalist.add(begin);
        } while (!begin.equals(end));
        //有效日期内每日订单总数
        List<Integer> orderCountList = new ArrayList<>();
        //有效日期内每日有效订单总数
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : datalist) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //统计每日订单
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
          Integer orderCount =  reportMapper.countBymap(map);
          //统计每日有效订单
            map.put("status",Orders.COMPLETED);
           Integer validOrderCount = reportMapper.countBymap(map);

           orderCountList.add(orderCount);
           validOrderCountList.add(validOrderCount);
        }
        //计算订单总数
        Integer totalorderCount = orderCountList.stream().reduce(Integer::sum).get();
        //计算有效订单
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //订单完成lv
        Double orderCompletionRate=0.0;
        if (validOrderCount > 0){
            orderCompletionRate =validOrderCount.doubleValue() / totalorderCount;
        }

        return  OrderReportVO.builder()
                .dateList(StringUtils.join(datalist,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalorderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }
/*
* 销量前十的商品
* */
    @Override
    public SalesTop10ReportVO top10statistics(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOList = reportMapper.getSalesTop10(beginTime, endTime);
        String nameList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()),",");
        String numberList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()),",");
        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();

    }
    /*
     * 导出Excel表格
     * */
    @Override
    public void export(HttpServletResponse response) {
        LocalDate beginDate = LocalDate.now().minusDays(30);
        LocalDate enddate = LocalDate.now().minusDays(1);

        //查询数据库，准备数据
        BusinessDataVO businessData = workSpaceService.getBusinessDate(LocalDateTime.of(beginDate, LocalTime.MIN), LocalDateTime.of(enddate, LocalTime.MAX));
        //通过poi操作Excel
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        //从已有Excel文件加载
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);

            XSSFSheet sheet = excel.getSheetAt(0);
            XSSFRow row = sheet.getRow(1);
            XSSFCell cell = row.getCell(1);

            cell.setCellValue(beginDate+"至"+enddate);

            //填充数据
           row =  sheet.getRow(3);
           cell = row.getCell(2);
           cell.setCellValue(businessData.getTurnover());

            cell = row.getCell(4);
            cell.setCellValue(businessData.getOrderCompletionRate());

            cell = row.getCell(6);
            cell.setCellValue(businessData.getNewUsers());

            row = sheet.getRow(4);
            cell = row.getCell(2);
            cell.setCellValue(businessData.getValidOrderCount());

            cell = row.getCell(4);
            cell.setCellValue(businessData.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                row = sheet.getRow(i + 7);
                LocalDate date = beginDate.plusDays(i);
                row.getCell(1).setCellValue(date.toString());

                BusinessDataVO businessDataVO = workSpaceService.getBusinessDate(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row.getCell(2).setCellValue(businessDataVO.getTurnover());
                row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            }
            //通过输出流将Excel文件下载到浏览器---输出流
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            out.flush();
            out.close();
            excel.close();


        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

